package com.gopay.scheduler.job;

import com.gopay.common.cps.dao.aggregatepayment.ApContractInfoQueryDAO;
import com.gopay.common.domain.aggregatepayment.ApContractInfo;
import com.gopay.common.util.DateUtils;
import com.gopay.scheduler.GopayBaseJob;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author lij-jiang
 * @ClassName: APMerAutoRenewalContractJob.java
 * @Description: 聚合支付-平安银行入驻商户自动续期合同
 * @date 2018年01月06日 16:29
 */
public class APMerAutoRenewalContractJob extends GopayBaseJob {

    private final Logger logger = LoggerFactory.getLogger(APMerAutoRenewalContractJob.class);

    @Resource(name = "apContractInfoQueryDAO")
    private ApContractInfoQueryDAO apContractInfoQueryDAO;

    @Override
    protected void doJobInternal() {
        logger.error("--聚合支付-平安银行入驻商户自动续期合同--start--");

        try {
            String status = "1";
            String autoSign = "1";
            Date nowDate = new Date();
            String endDate = DateUtils.format(nowDate, DateUtils.yyyy_MM_dd);
            logger.error("当前时间：endDate={}", endDate);

            // 查询出自动续约、小于等于今天合同到期、状态为已审核的商户合同
            List<ApContractInfo> oldContractInfoList = apContractInfoQueryDAO.getInfoByStatusAndEndDate(autoSign, status, endDate);

            if (oldContractInfoList != null && !oldContractInfoList.isEmpty()) {
                List<ApContractInfo> newContractInfoList = new ArrayList<>();
                for (ApContractInfo apContractInfo : oldContractInfoList) {
                    logger.error("要到期的商户：custId={},corpName={}", apContractInfo.getCustId(), apContractInfo.getCustName());
                    apContractInfo.setSdate(getCalendar(apContractInfo.getSdate()));
                    apContractInfo.setEdate(getCalendar(apContractInfo.getEdate()));
                    apContractInfo.setLastUpdTs(nowDate);
                    newContractInfoList.add(apContractInfo);
                }
                apContractInfoQueryDAO.saveOrUpdateAll(newContractInfoList);
            }
        } catch (Exception e) {
            logger.error("--聚合支付-平安银行入驻商户自动续期合同异常：", e);
        }

        logger.error("--聚合支付-平安银行入驻商户自动续期合同--end--");
    }

    private String getCalendar(String date) {
        if(StringUtils.isBlank(date)) {
            return "";
        }
        Date time = DateUtils.strToDate(date, DateUtils.yyyy_MM_dd);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.add(Calendar.YEAR, 1);
        return DateUtils.format(calendar.getTime(), DateUtils.yyyy_MM_dd);
    }
}
